using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace BlancoWorld.EventReceiversManager 
{
    public class EditEventReceiverPage : LayoutsPageBase
    {
        protected SPWeb _spWeb = null;
        protected SPList _spList = null;
        protected Guid _spListId = Guid.Empty;
        protected Guid _evRecId = Guid.Empty;
        protected SPEventReceiverDefinition _eventReceiver = null;
        protected SPGridView gridEventReceiverProperties;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            SiteMap.Providers["SPXmlContentMapProvider"].SiteMapResolve += new SiteMapResolveEventHandler(provider_SiteMapResolve);

            try
            {
                _spWeb = SPControl.GetContextWeb(Context);
                _spListId = new Guid(Server.UrlDecode(Request.QueryString["ListId"].ToString()));
                _spList = _spWeb.Lists[_spListId];
                _evRecId = new Guid(Server.UrlDecode(Request.QueryString["EvRecId"].ToString()));
                _eventReceiver = _spList.EventReceivers[_evRecId];
            }
            catch (Exception)
            {
                throw new Exception(String.Format("Unable to locate event receiver {0} for list {1}.",
                    _evRecId.ToString(), _spListId.ToString()));
            }
        }


        protected override void OnLoad(EventArgs e)
        {
            EventReceiverBinder erb = new EventReceiverBinder();
            erb.AddProperty("Type", _eventReceiver.Type.ToString());
            erb.AddProperty("ID", _eventReceiver.Id.ToString());
            erb.AddProperty("Assembly", _eventReceiver.Assembly);
            erb.AddProperty("Class Name", _eventReceiver.Class);
            erb.AddProperty("Sequence", _eventReceiver.SequenceNumber.ToString());

            erb.BindGrid(gridEventReceiverProperties);
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);

            //detach from the static SiteMapResolve event and restore localization mode              
            SiteMap.Providers["SPXmlContentMapProvider"].EnableLocalization = true;
            SiteMap.Providers["SPXmlContentMapProvider"].SiteMapResolve -= new SiteMapResolveEventHandler(provider_SiteMapResolve);
        }

        protected virtual bool IsSamePage(HttpContext context1, HttpContext context2)
        {
            //by default, the contexts are considered the same if they            
            //map to the same file and the same listid/itemid       
            return ((Server.MapPath(context1.Request.AppRelativeCurrentExecutionFilePath) ==
                Server.MapPath(context2.Request.AppRelativeCurrentExecutionFilePath)) &&
                (context1.Request.QueryString == context2.Request.QueryString));
        }

        protected void RedirectToSource()
        {
            string sourceUrl = Request.QueryString["SourceUrl"].ToString();
            Response.Redirect(sourceUrl);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            RedirectToSource();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            RedirectToSource();
        }

        protected SiteMapNode provider_SiteMapResolve(object sender, SiteMapResolveEventArgs e)
        {
            if (!IsSamePage(Context, e.Context))
            {
                e.Provider.EnableLocalization = true;
                return e.Provider.CurrentNode;
            }

            SiteMapNode pageTitleNode;
            SiteMapNode eventReceiversNode;
            SiteMapNode settingsNode;
            SiteMapNode listNode;
            try
            {
                // Trun off localization, so that the custom nodes do not get overwritten                 
                e.Provider.EnableLocalization = false;

                // Clone some node to get a valid node object and modify it.                 
                listNode = e.Provider.RootNode.ChildNodes[0].Clone();
                listNode.Url = _spList.DefaultViewUrl;
                listNode.Title = _spList.Title;
                listNode.ChildNodes = new SiteMapNodeCollection();

                // Add the settings node
                settingsNode = new SiteMapNode(e.Provider, Guid.NewGuid().ToString());
                settingsNode.Url = String.Format("{0}/_layouts/listedit.aspx?List={1}",
                    _spWeb.Url, Server.UrlEncode(_spList.ID.ToString()));
                settingsNode.Title = "Settings";
                settingsNode.ChildNodes = new SiteMapNodeCollection();
                listNode.ChildNodes.Add(settingsNode);
                settingsNode.ParentNode = listNode;

                // Add the event receivers node
                eventReceiversNode = new SiteMapNode(e.Provider, Guid.NewGuid().ToString());
                eventReceiversNode.Url = String.Format("{0}/_layouts/BlancoWorld.EventReceiversManager/EventReceiversManager.aspx?List={1}",
                    _spWeb.Url, Server.UrlEncode(_spList.ID.ToString()));
                eventReceiversNode.Title = "Event Receivers";
                eventReceiversNode.ChildNodes = new SiteMapNodeCollection();
                settingsNode.ChildNodes.Add(eventReceiversNode);
                eventReceiversNode.ParentNode = settingsNode;

                // Add the actual page node
                pageTitleNode = new SiteMapNode(e.Provider, Guid.NewGuid().ToString());
                pageTitleNode.Title = "Edit Event Receiver";
                eventReceiversNode.ChildNodes.Add(pageTitleNode);
                pageTitleNode.ParentNode = eventReceiversNode;
            }
            catch (Exception)
            {
                return e.Provider.CurrentNode;
            }
            return pageTitleNode;
        }
    }
}
